<template>

    <section>
        <div v-if="isRegistered" class="Form">
            <h1 class="title">П А Р * Л У С</h1>
            <h5 class="description">Самый корпоративный паролусный менеджер</h5>

            <InputText type="text" v-model="valueUsername" aria-describedby="username-help" @keyup.enter="enterSite" />
            <small id="username-help">Ваш логинус</small>
            
            <Password v-model="valuePassword" :feedback="false" aria-describedby="password-help" @keyup.enter="enterSite" />
            <small id="password-help">Ваш паролус</small>
            
            <Button @click="enterSite" label="Войти" icon="pi pi-chevron-right" iconPos="right" />
            <div v-if="canRegister">
                <p @click="toRegister">Быстрая регистрация</p>
            </div>
            <p @click="toAdmin">Панель администратора</p>
            <p @click="toGit">GitVerse</p>
        </div>

        <div v-else class="Form">
            <h1 class="title">П А Р * Л У С</h1>
            <h5 class="description">Самый безопасный паролусный менеджер</h5>

            <InputText type="text" v-model="valueUsername" aria-describedby="username-help" @keyup.enter="register" />
            <small id="username-help">Ваш логинус</small>

            <Password v-model="valuePassword" :feedback="false" aria-describedby="password-help" @keyup.enter="register" />
            <small id="password-help">Ваш паролус</small>

            <Password v-model="valuePasswordMatch" :feedback="false" aria-describedby="password-help" @keyup.enter="register" />
            <small id="password-help">Повторите паролус</small>
            
            <Button @click="register" label="Зарегистрироваться и войти" icon="pi pi-chevron-right" iconPos="right" />
            <p @click="toLogin">Назад</p>
        </div>
    <Toast />
    </section>

</template>
<script setup>
import InputText from 'primevue/inputtext';
import Password from 'primevue/password';
import Button from 'primevue/button';
import Toast from 'primevue/toast';
import store from '@/plugins/store';
import router from '@/plugins/router';

import { ref, watch, onBeforeMount } from 'vue';
import { useToast } from 'primevue/usetoast';


const toast = useToast();
const valueUsername = ref(null);
const valuePassword = ref(null);
const valuePasswordMatch = ref(null);
const isRegistered = ref(true);
const canRegister = ref(false);


// ---------------------------------------------------------------------------------------------->>>>>>>>> //
// ---------------------------------------------------------------------------------------------->>>>>>>>> //
// ---------------------------------------------------------------------------------------------->>>>>>>>> //
const selectedTheme = ref({ name: 'Аквамариновый', code: 'teal' });

function switchTheme() {
    const themeLink = document.getElementById('theme-link');
    store.dispatch('updateTheme', selectedTheme.value)
    themeLink.href = '/themes/lara-light-' + selectedTheme.value.code + '/theme.css';
}

onBeforeMount(() => {
  const storedTheme = localStorage.getItem('theme');
  if (storedTheme) {
    selectedTheme.value = JSON.parse(storedTheme);
    switchTheme(selectedTheme.value);
  };
  getConfig();
  canRegister.value = store.state.appConfig.enabled_registration;
});

watch(selectedTheme, (newTheme) => {
  localStorage.setItem('theme', JSON.stringify(newTheme));
  switchTheme(newTheme);
});

async function getConfig() {
    await store.dispatch('getAppConfig');
}

// ---------------------------------------------------------------------------------------------->>>>>>>>> //
// ---------------------------------------------------------------------------------------------->>>>>>>>> //
// ---------------------------------------------------------------------------------------------->>>>>>>>> //
async function enterSite() {
    if (valueUsername.value != null && valuePassword.value != null) {
        try {
            await store.dispatch('login', {
                username: valueUsername.value,
                password: valuePassword.value
            });
        } catch (error) {
            console.error('Error during login:', error);
            valueUsername.value = null;
            valuePassword.value = null;
            toast.add({ severity: 'error', summary: 'Ошибка', detail: 'Ошибка входа в систему', life: 3000 });
        }
    } else {
        console.log('Login error!');
        valueUsername.value = null;
        valuePassword.value = null;
        toast.add({ severity: 'error', summary: 'Ошибка', detail: 'Ошибка входа в систему', life: 3000 });
    }
}

async function register() {
    try {
        if (valuePassword.value == valuePasswordMatch.value && valuePassword.value != null) {
            await store.dispatch('register', {
                username: valueUsername.value,
                password: valuePassword.value
            });
            await store.dispatch('login', {
                username: valueUsername.value,
                password: valuePassword.value
            });
            store.dispatch('checkTokenExpiration');
        } else {
            console.log('valuePassword.value != valuePasswordMatch.value');
            valueUsername.value = null;
            valuePassword.value = null;
            valuePasswordMatch.value = null;
            toast.add({ severity: 'error', summary: 'Ошибка', detail: 'Паролусы не одинаковые', life: 3000 });
        }
    } catch (error) {
        console.error('Error during registration:', error);
        toast.add({ severity: 'error', summary: 'Ошибка', detail: 'Ошибка регистрации в системе', life: 3000 });
    }
}

// ---------------------------------------------------------------------------------------------->>>>>>>>> //
// ---------------------------------------------------------------------------------------------->>>>>>>>> //
// ---------------------------------------------------------------------------------------------->>>>>>>>> //
function toRegister() {
    isRegistered.value = false;
}

function toLogin() {
    isRegistered.value = true;
}

function toAdmin() {
    router.push('/admin');
}

function toGit() {
    window.open('https://gitverse.ru/internetfriend/parolus/', '_blank').focus();
}
</script>
<style scoped lang="css">
.Form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.title {
    color: var(--primary-color);
    margin: 0 0 0 0;
}
.Form:deep(input) {
    margin: 1rem;
}
.Form:deep(button) {
    margin: 1rem;
}
.Form p {
    cursor: pointer;
}

.Form p:hover {
    color: var(--primary-color);

    transition: 0.3s ease-in-out;
}
</style>